package com.shsubway.activity.staff;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.shsubway.R;
import com.shsubway.adapter.MyViewPagerAdapter;
import com.shsubway.base.BaseActivity;
import com.shsubway.fragment.QuestionFragment;
import com.shsubway.model.AnswerEntity;
import com.shsubway.model.QuestionEntity;
import com.shsubway.model.ScoreEntity;
import com.shsubway.model.StaffEntity;
import com.shsubway.model.TestEntity;
import com.shsubway.utils.BigDisMailUtils;
import com.shsubway.utils.Constant;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;

/**
 * 随机提
 * 1、情景设定获取是否管理员开启了 考试 如果是的话 获取随机值
 * 管理人员要设定题目的每个类型题目的数量 及分成比例
 * 2、如果没有开启 则进入自测随机设定
 */
public class RandomActivity extends BaseActivity {
    List<QuestionEntity> copyQues;//复制选题用于核对答案提交成绩
    List<QuestionEntity> allQues;//所有的随机题
    List<QuestionEntity> danQues_Q;//单选随机
    List<QuestionEntity> duoQues_Q;//多选随机
    List<QuestionEntity> panQues_Q;//多选随机
    int rightdan;//单选正确
    int rightduo;//多选正确
    double rightduowrong;//半对半错
    int rightpan;//判断正确
    int danNo;
    int duoNo;
    int panNo;
    int allQuesNo;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.page_no)
    TextView pageNo;
    @BindView(R.id.my_vp)
    ViewPager myVp;
    List<Fragment> fragmentList;
    MyViewPagerAdapter myViewPagerAdapter;
    String[] titles = {};
    @BindView(R.id.btn_edit)
    FloatingActionButton btnEdit;
    Map<String, Boolean> map;
    int coreDan = 0;
    int coreDuo = 0;
    int coreDuoW = 0;//半对半错
    int corePan = 0;//半对半错
    TestEntity testEntity = null;
    Intent intent;
    Bundle bundle;
    StaffEntity staffEntity;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_random);
        ButterKnife.bind(this);
        initView();
        initEvent();
    }

    private void initEvent() {

        myVp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                pageNo.setText((allQues.get(position).getQsttype() == 0 ? "单选题" : allQues.get(position).getQsttype() == 1 ? "多选题" : "判断题") + (position + 1) + "/" + fragmentList.size());

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void initView() {
        intent=getIntent();
        bundle=intent.getExtras();
        staffEntity= (StaffEntity) bundle.getSerializable(Constant.STAFFENTITY);
        map = new HashMap<>();
        fragmentList = new ArrayList<>();
        allQues = new ArrayList<>();
        copyQues = new ArrayList<>();
        danQues_Q = new ArrayList<>();
        duoQues_Q = new ArrayList<>();
        panQues_Q = new ArrayList<>();
        getTestMsg();
    }

    private void getTestMsg() {
        //// TODO: 2017/3/7 在录入员工后 记得更换
        BmobQuery<TestEntity> testEntityBmobQuery = new BmobQuery<>();
        testEntityBmobQuery.addWhereEqualTo("groupId", staffEntity.getGroupId());
        testEntityBmobQuery.findObjects(new FindListener<TestEntity>() {
            @Override
            public void done(List<TestEntity> list, BmobException e) {
                if (e == null) {
                    if (list.size() != 0) {
                        testEntity = list.get(list.size() - 1);
                        danNo = testEntity.getDanNo();
                        coreDan = testEntity.getDanScore();
                        duoNo = testEntity.getDuoNo();
                        coreDuo = testEntity.getDuoScore();
                        coreDuoW = testEntity.getScoreWrong();
                        panNo = testEntity.getPanNo();
                        corePan = testEntity.getPanScore();
                        allQuesNo = testEntity.getDanNo() + testEntity.getDuoNo() + testEntity.getPanNo();
                        setTitleBar(toolbar, testEntity.isOpen() ? "考试模式" : "自测模式");
                        getFromNet();
                    }
                } else {

                }
                toolbar.setNavigationOnClickListener(v -> finish());
            }
        });


    }

    private void getFromNet() {
        List<BmobQuery<QuestionEntity>> queries = new ArrayList<BmobQuery<QuestionEntity>>();
        for (int i = 0; i < 3; i++) {
            BmobQuery<QuestionEntity> eq = new BmobQuery<QuestionEntity>();
            if (i == 0) {
                if (danNo != 0) {
                    eq.addWhereEqualTo("qsttype", 0);
                }
            } else if (i == 1) {
                if (duoNo != 0) {
                    eq.addWhereEqualTo("qsttype", 1);
                }
            } else if (i == 2) {
                if (panNo != 0) {
                    eq.addWhereEqualTo("qsttype", 2);
                }
            }
            queries.add(eq);
        }
        BmobQuery<QuestionEntity> questionEntityBmobQuery = new BmobQuery<QuestionEntity>();
        questionEntityBmobQuery.or(queries);
        questionEntityBmobQuery.setLimit(1000);
        questionEntityBmobQuery.findObjects(new FindListener<QuestionEntity>() {
            @Override
            public void done(List<QuestionEntity> list, BmobException e) {
                if (e == null) {
                    distribution(list);
                    creatAdapter();
                } else {
                    toast("获取失败，请联系直属领导。");
                }
            }
        });
    }

    private void creatAdapter() {
        for (QuestionEntity questionEntity : allQues) {
            QuestionFragment questionFragment = new QuestionFragment();
            questionFragment.setQues(questionEntity, 0);
            fragmentList.add(questionFragment);
        }
        pageNo.setText((allQues.get(0).getQsttype() == 0 ? "单选题" : allQues.get(0).getQsttype() == 1 ? "多选题" : "判断题") + (1) + "/" + fragmentList.size());
        Log.e("SIZE==", fragmentList.size() + "");
        Log.e("allQuesNo==", allQuesNo + "");
        if (fragmentList.size() == allQuesNo) {
            initAdapter();

        } else {
            toast("随机获取失败，正在重新获取请稍后。");
            fragmentList.clear();
            copyQues.clear();
            allQues.clear();
            danQues_Q.clear();
            duoQues_Q.clear();//多选随机
            panQues_Q.clear();//多选随机
            getFromNet();
        }


    }

    private void initAdapter() {
        myViewPagerAdapter = new MyViewPagerAdapter(getSupportFragmentManager(), fragmentList, titles);
        myVp.setAdapter(myViewPagerAdapter);
    }

    /**
     * 获取总的题库 然后进行类型的筛选
     */
    private void distribution(List<QuestionEntity> list) {
        //1、初始化list
        List<QuestionEntity> danQues = new ArrayList<>();//单选随机
        List<QuestionEntity> duoQues = new ArrayList<>();//多选随机
        List<QuestionEntity> panQues = new ArrayList<>();//多选随机
        //2.对已经查出的list 进行分类
        for (QuestionEntity questionEntity : list) {
            if (questionEntity.getQsttype() == 0) {
                danQues.add(questionEntity);
            } else if (questionEntity.getQsttype() == 1) {
                duoQues.add(questionEntity);
            } else if (questionEntity.getQsttype() == 2) {
                panQues.add(questionEntity);
            }
        }
        //3、生成随机list的对象
        for (int i = 0; i < 3; i++) {
            HashSet<Integer> integerHashSetdan = new HashSet();
            if (i == 0) {
                if (danNo != 0) {
                    //1、初始化set 获取随机数字
                    randomSet(0, danQues.size(), danNo, integerHashSetdan);
                    //2、通过set获取list的随机对象
                    addDate(integerHashSetdan, danQues, danQues_Q);
                }
            } else if (i == 1) {
                if (duoNo != 0) {
                    //1、初始化set 获取随机数字
                    randomSet(0, duoQues.size(), duoNo, integerHashSetdan);
                    //2、通过set获取list的随机对象
                    addDate(integerHashSetdan, duoQues, duoQues_Q);
                }

            } else if (i == 2) {
                if (panNo != 0) {
                    //1、初始化set 获取随机数字
                    randomSet(0, panQues.size(), panNo, integerHashSetdan);
                    //2、通过set获取list的随机对象
                    addDate(integerHashSetdan, panQues, panQues_Q);
                }
            }
        }
    }

    private void addDate(HashSet<Integer> set, List<QuestionEntity> rq, List<QuestionEntity> q_Q) {
        for (Integer integer : set) {
            q_Q.add(rq.get(integer));
        }
        //拷贝list作为对照答案

//        copyQues.addAll(q_Q);
        //对所有checkbox进行初始化
        for (QuestionEntity questionEntity : q_Q) {
            QuestionEntity questionEntity1 = new QuestionEntity();
            questionEntity1.setObjectId(questionEntity.getObjectId());
            questionEntity1.setQsttype(questionEntity.getQsttype());
            questionEntity1.setQstcontent(questionEntity.getQstcontent());
            List<AnswerEntity> entityList = questionEntity.getAnswerEntities();
            List<AnswerEntity> entityListnew = new ArrayList<>();
            for (AnswerEntity answerEntity : entityList) {
                AnswerEntity answerEntity1 = new AnswerEntity();
                answerEntity1.setObjectId(answerEntity.getObjectId());
                answerEntity1.setTure(answerEntity.isTure());
                entityListnew.add(answerEntity1);
                answerEntity.setTure(false);
            }
            questionEntity1.setAnswerEntities(entityListnew);
            copyQues.add(questionEntity1);
        }
        allQues.addAll(q_Q);
    }

    /**
     * 随机指定范围内N个不重复的数
     * 利用HashSet的特征，只能存放不同的值
     *
     * @param min          指定范围最小值
     * @param max          指定范围最大值
     * @param n            随机数个数
     * @param set<Integer> set 随机数结果集
     */
    public static void randomSet(int min, int max, int n, HashSet<Integer> set) {
        if (n > (max - min + 1) || max < min) {
            return;
        }
        for (int i = 0; i < n; i++) {
            // 调用Math.random()方法
            int num = (int) (Math.random() * (max - min)) + min;
            set.add(num);// 将不同的数存入HashSet中
        }
        int setSize = set.size();
        // 如果存入的数小于指定生成的个数，则调用递归再生成剩余个数的随机数，如此循环，直到达到指定大小
        if (setSize < n) {
            randomSet(min, max, n - setSize, set);// 递归
        }
    }

    @OnClick(R.id.btn_edit)
    public void onClick() {
        showAskDialog();
    }

    private void showAskDialog() {

        /* @setIcon 设置对话框图标
         * @setTitle 设置对话框标题
         * @setMessage 设置对话框消息提示
         * setXXX方法返回Dialog对象，因此可以链式设置属性
         */
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(context);
        normalDialog.setIcon(R.mipmap.ic_launcher);
        normalDialog.setTitle("提示：提交后无法再撤回");
        normalDialog.setMessage("你确定要提交成绩吗？");
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                        comit();

                    }
                });
        normalDialog.setNegativeButton("关闭",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                    }
                });
        // 显示
        normalDialog.show();
    }

    private void comit() {
        double allCore = getCore();

        ScoreEntity scoreEntity = new ScoreEntity();
        scoreEntity.setScore(allCore);
        scoreEntity.setUserId(staffEntity.getObjectId());
        scoreEntity.setUserName(staffEntity.getStaff_name());
        //0为单位考试 1为自测模式
        scoreEntity.setTestType(testEntity.isOpen() ? 0 : 1);
        scoreEntity.setTestId(testEntity.isOpen() ? testEntity.getObjectId() : "0");
        scoreEntity.setDanNo(rightdan);
        scoreEntity.setDanNoAll(danQues_Q.size());

        scoreEntity.setDuoNo(rightduo);
        scoreEntity.setDuoWrongNo(rightduowrong);
        scoreEntity.setDuoNoAll(duoQues_Q.size());

        scoreEntity.setPanNo(rightpan);
        scoreEntity.setPanNoAll(panQues_Q.size());
        scoreEntity.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (e == null) {
                    toast("提交成功，考试成绩" + allCore + "分" + "\n" + "正确率：" + BigDisMailUtils.turnTrim(((Double.valueOf(rightdan + rightduo + rightduowrong + rightpan) * 100) / allQues.size()), 2) + "%");
                   setResult(1);
                    finish();
                } else {
                    toast("提交失败，请联系直属领导");
                }
            }
        });

    }

    private int getCore() {
        int coreAll = 0;
        for (int i = 0; i < allQues.size(); i++) {
            int duocore = 0;
            QuestionEntity questionEntity = allQues.get(i);
            QuestionEntity questionEntityCopy = copyQues.get(i);
            List<AnswerEntity> answerEntities = questionEntity.getAnswerEntities();
            List<AnswerEntity> answerEntitiesCopy = questionEntityCopy.getAnswerEntities();
            boolean isOk = false;
            boolean isLo = false;
            //对做的题目先进行非空判断 如果为为true 则进行下一步判断  如果返回false 则给0分
            if (getIsEmpty(answerEntities)) {
                for (int j = 0; j < answerEntities.size(); j++) {
                    //如果是判断和单选题
                    if (questionEntity.getQsttype() != 1) {
                        if (String.valueOf(answerEntities.get(j).isTure()).equals(String.valueOf(answerEntitiesCopy.get(j).isTure()))) {
                            isOk = true;
                        } else {
                            isOk = false;
                            break;
                        }
                    } else {
                        //如果是多选题
//                    // 选错一个即没有分数
//                    //先对选项和备份答案进行比对
//                    //1、对这道多选题 进行空选判断
                        if (String.valueOf(answerEntities.get(j).isTure()).equals(String.valueOf(answerEntitiesCopy.get(j).isTure()))) {
                            isOk = true;
                            //如果是漏选了 那么不能给全分
                            if (isLo) {
                                duocore = coreDuoW;
                            } else {
                                duocore = coreDuo;
                            }
                        } else {
                            if (!answerEntities.get(j).isTure()) {
                                isLo = true;
                                duocore = coreDuoW;
                            } else {
                                isLo = false;
                                isOk = false;
                                duocore = 0;
                                break;
                            }
                        }


                    }

                }
            }
            if (isOk) {
                if (questionEntity.getQsttype() == 1) {


                    coreAll = coreAll + duocore;
                    if (duocore == coreDuo) {
                        rightduo++;
                    } else if (duocore == coreDuoW) {
                        rightduowrong = rightduowrong + 0.5;
                    }


                } else if (questionEntity.getQsttype() == 0) {
                    //暂定单选和判断一样的分值
                    coreAll = coreAll + coreDan;
                    rightdan++;
                } else if (questionEntity.getQsttype() == 2) {
                    coreAll = coreAll + corePan;
                    rightpan++;
                }
            }

        }

        return coreAll;
    }

    private boolean getIsEmpty(List<AnswerEntity> answerEntities) {
        for (AnswerEntity ans : answerEntities) {
            if (ans.isTure()) {
                return true;
            }
        }
        return false;
    }
}
